package service

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"strconv"
)

func HelloEs() {
	addBlogUserJson()
}

var client *elastic.Client
var Index = "school_1"
var Type = "class_1"

func init() {
	//es.InitClient() //初始化client
	//client = es.Client
}

// Person 数据结构体
type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
	Like string `json:"like"`
}

// 添加一条数据
func addPerson() {
	//添加数可以用结构体方式和 json字符串方式
	p := Person{"张良", 25, "围棋"}
	//p := `{"name":"张良","age":25,"like":"围棋"}`
	put, err := client.Index().Index(Index).Type(Type).Id("1").BodyJson(p).Do(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Printf("indexed %s --- index %s --- type %s \n", put.Id, put.Index, put.Type)
}

/*
PUT /blog/user/4
{"id":4,"user_name":"赵六","password":"123456"}
*/

var BlogIndex = "blog"
var BlogUserTable = "user"

// 添加数据到blog - 字符串添加
func addBlogUser() {
	u := `{"id":4,"user_name":"赵六","password":"123456"}`
	put, err := client.Index().Index(BlogIndex).Type(BlogUserTable).Id("1").BodyString(u).Do(context.Background())
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("indexed %s --- index %s --- type %s \n", put.Id, put.Index, put.Type)
}

type User struct {
	Id       int
	UserName string
	Password string
}

// 添加数据到blog - json添加
func addBlogUserJson() {
	u := User{
		UserName: "王志华",
		Password: "1234",
		Id:       19,
	}
	put, err := client.Index().Index(BlogIndex).Type(BlogUserTable).Id(strconv.Itoa(u.Id)).BodyJson(u).Do(context.Background())
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(put)
}
